package com.hhd.pdf.components;

import com.hhd.pdf.context.GeneratorContext;
import com.hhd.pdf.utils.PdfUtils;
import com.hhd.pdf.variable.VariableContext;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.hhd.pdf.CommonUtils;
import org.dom4j.Attribute;
import org.dom4j.tree.DefaultElement;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collection;
import java.util.List;

@Component
public class Autograph extends AbstractInLineBlockComponent {

    @Override
    public List<Element> createElements(org.dom4j.Element element,
                                        GeneratorContext context,
                                        VariableContext rootVariableContext) throws DocumentException, IOException {
        String formula = null;
        try {
            formula = getFormula((DefaultElement) element);
        } catch (Exception e) {
            return CommonUtils.newList();
        }
        String formulaStringValue = getFormulaStringValue(formula, rootVariableContext);
        if (CommonUtils.isEmpty(formulaStringValue)) return CommonUtils.newList();
        Image autograph = PdfUtils.getAutographByPath(formulaStringValue);
        autograph.scalePercent(60);
        autograph.setAlignment(Element.ALIGN_CENTER);
        return CommonUtils.newList(autograph);
    }

    @Override
    public String getFormula(DefaultElement defaultElement) {
        Attribute src = defaultElement.attribute("src");
        return src.getText();
    }

    @Override
    public Collection<? extends Element> createPdfElement(DefaultElement defaultElement,
                                                          GeneratorContext context,
                                                          String parsedFormula) throws DocumentException, IOException {
        if (CommonUtils.isEmpty(parsedFormula)) {
            return CommonUtils.newList();
        }
        Image autograph = PdfUtils.getAutograph(parsedFormula);
        autograph.scalePercent(60);
        autograph.setAlignment(Element.ALIGN_CENTER);
        return CommonUtils.newList(autograph);
    }

    @Override
    public String getName() {
        return "autograph";
    }
}
